package com.example.gkcircle.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by Jehu on 16/3/20.
 */
//监听输入字符长度
public  class TextWatcherListener implements TextWatcher {

    private EditText editText;
    private TextView textView;
    private CharSequence temp;
    private int editStart;
    private int editEnd;
    private int maxLength;

    public TextWatcherListener(TextView textView,EditText editText,int maxLength) {
        this.maxLength = maxLength;
        this.textView=textView;
        this.editText=editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        temp = s;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        editStart = this.editText.getSelectionStart();
        editEnd = this.editText.getSelectionEnd();
        if(temp.length() <= maxLength){
            this.textView.setText(maxLength - temp.length()+"");
        }else{
            s.delete(editStart - 1, editEnd);
            int tempSelection = editStart;
            this.editText.setText(s);
            this.editText.setSelection(tempSelection);
        }
    }
}
